// API基础配置
const API_BASE_URL = '/listening_manager/api';

// 统一请求函数
async function apiRequest(url, method = 'POST', data = null) {
    try {
        const config = {
            method,
            url: `${API_BASE_URL}${url}`,
            headers: {
                'Content-Type': 'application/json'
            }
        };

        if (data) {
            config.data = data;
        }

        const response = await axios(config);

        // 统一处理响应
        if (response.data && response.data.code === 200) {
            return response.data;
        } else if (response.data && response.data.code === 401) {
            // 未授权，跳转到登录页
            Auth.clearUser();
            window.location.href = 'login.html';
            return null;
        } else {
            // 显示后端返回的错误信息
            const errorMessage = response.data.message || '请求失败';
            throw new Error(errorMessage);
        }
    } catch (error) {
        console.error('API请求错误:', error);
        if (error.response && error.response.data) {
            // 显示后端返回的错误信息
            const errorMessage = error.response.data.message || '请求失败';
            throw new Error(errorMessage);
        } else {
            throw new Error(error.message || '网络错误，请稍后重试');
        }
    }
}

// 系统相关API
const sysApi = {
    // 登录
    login: (username, password) => apiRequest('/sys/login', 'POST', { username, password }),

    // 退出登录
    logout: () => apiRequest('/sys/logout', 'POST'),

    // 修改密码
    updatePassword: (oldPassword, newPassword) =>
        apiRequest('/sys/updatePassword', 'POST', { oldPassword, newPassword }),

    // 获取网站标题
    getTitle: () => apiRequest('/sys/getTitle', 'POST'),

    // 更新网站标题
    updateTitle: (title) => apiRequest('/sys/updateTitle', 'POST', { title })
};

// 分类相关API
const categoryApi = {
    // 一级分类
    level1: {
        list: () => apiRequest('/category/level1/list', 'POST'),
        add: (category) => apiRequest('/category/level1/add', 'POST', category),
        update: (category) => apiRequest('/category/level1/update', 'POST', category),
        delete: (categoryId) => apiRequest('/category/level1/delete', 'POST', { categoryId })
    },

    // 二级分类
    level2: {
        list: () => apiRequest('/category/level2/list', 'POST'),
        listByCategory: (categoryId) => apiRequest('/category/level2/listByCategory', 'POST', { categoryId }),
        add: (subcategory) => apiRequest('/category/level2/add', 'POST', subcategory),
        update: (subcategory) => apiRequest('/category/level2/update', 'POST', subcategory),
        delete: (subcategoryId) => apiRequest('/category/level2/delete', 'POST', { subcategoryId })
    }
};
// 听力文件相关API
const audioApi = {
    list: () => apiRequest('/audio/list', 'POST'),
    listByCategory: (params) => apiRequest('/audio/listByCategory', 'POST', params),
    search: (keyword) => apiRequest('/audio/search', 'POST', { keyword }),
    upload: (formData) => {
        return axios.post(`${API_BASE_URL}/audio/upload`, formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            },
            timeout: 300000,
            withCredentials: true
        }).then(response => {
            if (response.data && response.data.code === 200) {
                return response.data;
            } else if (response.data && response.data.code === 401) {
                Auth.clearUser();
                window.location.href = 'login.html';
                return null;
            } else {
                throw new Error(response.data.message || '上传失败');
            }
        }).catch(error => {
            if (error.response && error.response.data) {
                if (error.response.data.code === 401) {
                    Auth.clearUser();
                    window.location.href = 'login.html';
                    return null;
                }
                throw new Error(error.response.data.message || '上传失败');
            }
            throw error;
        });
    },
    update: (audioFile) => apiRequest('/audio/update', 'POST', audioFile),
    delete: (audioId) => apiRequest('/audio/delete', 'POST', { audioId }),
    play: (audioId) => apiRequest('/audio/play', 'POST', { audioId }),
    download: (audioId) => apiRequest('/audio/download', 'POST', { audioId })
};